package com.erp.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.ae.api.RemoteAeLogisticsService;
import com.ruoyi.ae.api.domain.AeHandoverCommitInfo;
import com.erp.order.domain.ErpHandoverOrdersInfo;
import com.erp.order.domain.ErpSellerHandoverOrder;
import com.erp.order.domain.ErpWarehouseOrderInfo;
import com.erp.order.domain.bo.ErpHandoverOrdersInfoSelBo;
import com.erp.order.domain.vo.ErpHandoverOrdersInfoSelVo;
import com.erp.order.mapper.*;
import com.erp.order.service.IAeHandoverOrdersService;
import com.erp.order.service.IAeOrderService;
import com.erp.order.service.IErpSellerOrderLogService;
import com.erp.order.service.IErpSellerOrderService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.order.api.domain.*;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpowerExtend;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class AeHandoverOrdersServiceImpl implements IAeHandoverOrdersService {

    private final ErpWarehouseOrderInfoMapper erpWarehouseOrderInfoMapper;
    private final ErpSellerOrderMapper erpSellerOrderMapper;
    private final ErpSellerOrderExtendMapper sellerOrderExtendMapper;
    private final IErpSellerOrderLogService orderLogService;
    private final IErpSellerOrderService iErpSellerOrderService;
    private final ErpHandoverOrdersInfoMapper erpHandoverOrdersInfoMapper;
    private final ErpSellerOrderLogMapper erpSellerOrderLogMapper;
    private final ErpSellerChildOrderExtendMapper erpSellerChildOrderExtendMapper;
    private final ErpSellerChildOrderMapper erpSellerChildOrderMapper;
    private final RemoteSellerStoreService remoteSellerStoreService;
    private final RemoteAeLogisticsService remoteAeLogisticsService;
    private final IAeOrderService aeOrderService;

    @Transactional
    @Override
    public R<Object> handoverCommitAuto() {
        List<ErpSellerOrder> orderList = erpSellerOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerOrder>()
                        .eq(ErpSellerOrder::getErpInnerOrderStatus, 109)
        );
        //校验这些order中，是否有没有声明发货的
        StringBuffer errorStr = new StringBuffer();
        for (ErpSellerOrder order : orderList) {
            if (!order.getOrderStatus().equals("WAIT_BUYER_ACCEPT_GOODS")){

                R<Object> orderBaseInfo = aeOrderService.findOrderIssueInfo(order.getOrderId());
                if (orderBaseInfo != null && orderBaseInfo.getCode() == 200) {
                    Map<String, Object> data = (Map<String, Object>) orderBaseInfo.getData();
                    String dataStr = (String) data.get("data");
                    JSONObject jsonObject = JSONObject.parseObject(dataStr);

                   
                    String logisticsStatus = jsonObject
                            .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
                            .getJSONObject("result")
                            .getString("logistics_status");
                    String issueStatus = jsonObject
                            .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
                            .getJSONObject("result")
                            .getString("issue_status");

                    ErpSellerOrderExtend orderExtend = sellerOrderExtendMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, order.getOrderId()));
                    if (orderExtend == null) {
                        orderExtend = new ErpSellerOrderExtend();
                        orderExtend.setOrderId(order.getOrderId());
                    }
                    orderExtend.setLogisticsType(logisticsStatus);
                    orderExtend.setIssueStatus(issueStatus);
                    sellerOrderExtendMapper.insertOrUpdate(orderExtend);
                    
                    String orderStatus = jsonObject
                            .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
                            .getJSONObject("result")
                            .getString("order_status");

                    if (orderStatus.equals("WAIT_BUYER_ACCEPT_GOODS")){
                        order.setOrderStatus(orderStatus);
                        erpSellerOrderMapper.updateById(order);
                    }else {
                        errorStr.append("订单号："+order.getOrderId());
                        errorStr.append("订单状态不为待收货||");
                    }
                }
            }else {
                List<ErpSellerOrderLog> logList= erpSellerOrderLogMapper.selectList(
                        new LambdaQueryWrapper<ErpSellerOrderLog>()
                                .eq(ErpSellerOrderLog::getOrderId,order.getOrderId())
                                .eq(ErpSellerOrderLog::getType,"24")
                );
                if (logList.size() == 0){
                    errorStr.append("订单号："+order.getOrderId());
                    errorStr.append("日志中没有声明发货记录||");
                }
            }
        }
        if (errorStr.toString().contains("订单号")){
            return R.fail(errorStr.toString(),null);
        }

        List<Long> orderIdList = orderList.stream().map(e -> e.getOrderId()).collect(Collectors.toList());
        String orderIds = orderIdList.stream()
                .map(String::valueOf)
                .reduce((a, b) -> a + "," + b)
                .orElse("");
        System.out.println(orderIds);


        return handoverCommit(orderIds);
    }


    @Transactional
    @Override
    public R<Object> handoverCommit(String orderIds) {
        List<String> orderIdlist = Arrays.asList(orderIds.split(","));

        List<ErpWarehouseOrderInfo> warehouseOrderList = erpWarehouseOrderInfoMapper.getWarehouseOrderByOrderIds(orderIdlist);

        StringBuffer orderCodeList = new StringBuffer();
        StringBuffer childIdList = new StringBuffer();
        StringBuffer storeList = new StringBuffer();
        String storeId = null;
        Long addressId = null;
        //创建外层map
        Map<String, Object> storeAllMap = new HashMap<>();
        ErpSellerStoreEmpower store = new ErpSellerStoreEmpower();
        for (int i = 0; i < warehouseOrderList.size(); i++) {
            storeId = warehouseOrderList.get(i).getSellerId();
            storeList.append(storeId);

            //创建内层map
            Map<String, Object> storeMap = (Map<String, Object>) storeAllMap.get(storeId);
            if (storeMap == null) {
                storeMap = new HashMap<>();
                R<Object> sellerStoreInfoById = remoteSellerStoreService.getSellerStoreInfoById(Long.valueOf(storeId));
                store = JSONObject.parseObject(JSON.toJSONString(sellerStoreInfoById.getData()), ErpSellerStoreEmpower.class);
                storeMap.put("user_nick", store.getStoreUserName());
            }

            //将店铺中的将orderCode取出更新
            StringBuffer storeOrderCodeList = new StringBuffer();
            if ((String) storeMap.get("order_code_list") != null) {
                storeOrderCodeList = new StringBuffer((String) storeMap.get("order_code_list"));
            }

            //3、将childList整理成字符串
            childIdList.append(warehouseOrderList.get(i).getChildOrderId());
            storeOrderCodeList.append(warehouseOrderList.get(i).getOutOrderCode());

            if (i != warehouseOrderList.size() - 1) {
                childIdList.append(",");
                storeOrderCodeList.append(",");
                storeList.append(",");
            }

            storeMap.put("order_code_list", storeOrderCodeList.toString());
            storeAllMap.put(storeId, storeMap);


        }

        R<Object> sellerStoreInfoById = remoteSellerStoreService.getSellerStoreInfoById(Long.valueOf(storeId));
        store = JSONObject.parseObject(JSON.toJSONString(sellerStoreInfoById.getData()), ErpSellerStoreEmpower.class);

        //生成交接单对象，并查看该对象是否已经存在过
        ErpHandoverOrdersInfo erpHandoverOrderInfo = new ErpHandoverOrdersInfo();

        AeHandoverCommitInfo handoverOrderInfo = new AeHandoverCommitInfo();
        handoverOrderInfo.setSellerId(store.getId().toString());
        //主要挂钩店铺id
        erpHandoverOrderInfo.setMainStoreId(store.getId().toString());
        erpHandoverOrderInfo.setMainStoreName(store.getStoreUserName());
        //所包含店铺ids
        erpHandoverOrderInfo.setStoreIds(storeList.toString());
        //所包含orderId
        erpHandoverOrderInfo.setOrderIds(orderIds);

        //用户信息
        List<AeHandoverCommitInfo.SellerParcelOrderList> seller_parcel_order_list = new ArrayList<>();

        for (String key : storeAllMap.keySet()) {
            Map<String, Object> storeForMap = (Map<String, Object>) storeAllMap.get(key);
            AeHandoverCommitInfo.SellerParcelOrderList sellerParcelOrderList = new AeHandoverCommitInfo.SellerParcelOrderList();
            sellerParcelOrderList.setUser_nick((String) storeForMap.get("user_nick"));
            String storeOrderCode = (String) storeForMap.get("order_code_list");
            sellerParcelOrderList.setOrder_code_list(storeOrderCode.split(","));
            seller_parcel_order_list.add(sellerParcelOrderList);
        }


        handoverOrderInfo.setSeller_parcel_order_list(seller_parcel_order_list);
        erpHandoverOrderInfo.setOrderCodeList(JSONObject.toJSONString(storeAllMap));
        //子订单id列表
        erpHandoverOrderInfo.setChildOrderIds(childIdList.toString());

        //查找Order出库OC号
        List<ErpSellerChildOrderExtend> childOrderExtends = erpSellerChildOrderExtendMapper.selectChildOrderExtendByOrderIds(orderIdlist);
        StringBuffer consignmentNoStr = new StringBuffer();
        for (int i = 0; i < childOrderExtends.size(); i++) {
            String consignmentNo = childOrderExtends.get(i).getConsignmentNo();
            if (consignmentNoStr.toString().contains(consignmentNo)) {
                continue;
            }
            ErpWarehouseOrderInfo warehouseOrderInfo = erpWarehouseOrderInfoMapper.selectOne(
                    new LambdaQueryWrapper<ErpWarehouseOrderInfo>().eq(ErpWarehouseOrderInfo::getChildOrderId, childOrderExtends.get(i).getChildOrderId())
            );
            consignmentNoStr.append(childOrderExtends.get(i).getConsignmentNo());
            consignmentNoStr.append("-");
            consignmentNoStr.append(warehouseOrderInfo.getIntlTrackingNo());
            if (i != childOrderExtends.size() - 1) {
                consignmentNoStr.append(",");
            }
        }

        //大包备注;大包备注
        erpHandoverOrderInfo.setRemark("OC号-国际物流单号：" + consignmentNoStr.toString());
        //揽收地址
        AeHandoverCommitInfo.PickupInfo pickupInfo = new AeHandoverCommitInfo.PickupInfo();
        AeHandoverCommitInfo.Address address = new AeHandoverCommitInfo.Address();
        pickupInfo.setAddress_id(addressId);
        //广东省深圳市宝安区福海街道福海街道福园一路德工业园骏捷云仓宿舍楼B1栋1，AE182739
        address.setDetail_address("福园一路德工业园骏捷云仓宿舍楼B1栋1");
        address.setStreet("福海街道");
        address.setDistrict("宝安区");
        address.setCity("深圳市");
        address.setProvince("广东省");
        address.setCountry("中国");
        pickupInfo.setName("李俊AE182739");
        pickupInfo.setMobile("15814661691");
        pickupInfo.setAddress(address);
        handoverOrderInfo.setPickup_info(pickupInfo);
        erpHandoverOrderInfo.setPickupInfo(addressId);

        //每个商家在ISV系统的唯一标识，一般为商家ISV账号的id
        AeHandoverCommitInfo.UserInfo userInfo = new AeHandoverCommitInfo.UserInfo();
        ErpSellerStoreEmpowerExtend searchStoreExtend = new ErpSellerStoreEmpowerExtend();
        searchStoreExtend.setSellerId(Long.valueOf(storeId));
        R<Object> sellerStoreExtendInfo = remoteSellerStoreService.getSellerStoreExtendInfo(searchStoreExtend);
        ErpSellerStoreEmpowerExtend storeExtend = JSONObject.parseObject(JSONObject.toJSONString(sellerStoreExtendInfo.getData()), ErpSellerStoreEmpowerExtend.class);
        userInfo.setTop_user_key(storeExtend.getUserId());
        handoverOrderInfo.setUser_info(userInfo);
        erpHandoverOrderInfo.setUserInfo(storeExtend.getUserId());

        /**
         * 交接单类型：cainiao_pickup(菜鸟揽收)、self_post(自寄)、self_send(自送)
         */
        handoverOrderInfo.setType("cainiao_pickup");
        erpHandoverOrderInfo.setType("cainiao_pickup");
        /**
         * ISV名称，ISV：ISV-ISV英文或拼音名称、商家ERP：SELLER-商家英文或拼音名称
         */
        handoverOrderInfo.setClient("SELLER-" + store.getStoreUserName());
        erpHandoverOrderInfo.setClient("SELLER-" + store.getStoreUserName());
        /**
         * 多语言
         */
        handoverOrderInfo.setLocale("zh_CN");
        erpHandoverOrderInfo.setLocale("zh_CN");
        /**
         * 预约交货方式（bigbag：大包预约，batch：批次预约））
         */
        handoverOrderInfo.setAppointment_type("bigbag");

        //提交交接单至Ae
        R<Object> objectR = remoteAeLogisticsService.handoverCommit(handoverOrderInfo);
        
        //解析信息
        String body = JSONObject.toJSONString(objectR.getData());
        Integer code = (Integer) JSONObject.parseObject(body).get("code");
        if (code == 200) {
            //交接物id，即大包id
            erpHandoverOrderInfo.setHandoverContentId(
                    Long.valueOf(JSONObject.parseObject(body)
                            .getJSONObject("msg")
                            .getJSONObject("cainiao_global_handover_commit_response")
                            .getJSONObject("result")
                            .getJSONObject("data")
                            .getString("handover_content_id"))
            );
            handoverOrderInfo.setHandover_content_id(erpHandoverOrderInfo.getHandoverContentId());
            //交接物编码，即大包LP号
            erpHandoverOrderInfo.setHandoverContentCode(
                    JSONObject.parseObject(body)
                            .getJSONObject("msg")
                            .getJSONObject("cainiao_global_handover_commit_response")
                            .getJSONObject("result")
                            .getJSONObject("data")
                            .getString("handover_content_code")
            );
            handoverOrderInfo.setHandover_content_code(erpHandoverOrderInfo.getHandoverContentCode());
            //交接批次号，即交接单id
            erpHandoverOrderInfo.setHandoverOrderId(
                    Long.valueOf(JSONObject.parseObject(body)
                            .getJSONObject("msg")
                            .getJSONObject("cainiao_global_handover_commit_response")
                            .getJSONObject("result")
                            .getJSONObject("data")
                            .getString("handover_order_id"))
            );
            handoverOrderInfo.setHandover_order_id(erpHandoverOrderInfo.getHandoverOrderId());

            for (ErpWarehouseOrderInfo warehouseOrderInfo : warehouseOrderList) {
                //交接单状态改为已发货
                warehouseOrderInfo.setStatus(2);
                erpWarehouseOrderInfoMapper.updateById(warehouseOrderInfo);
            }

            // 将数据存到数据库中
            //获取交接单详细信息
            handoverContentQuery(erpHandoverOrderInfo);

            //增加日志 订单组包成功 并将订单改为115
            for (String orderId : orderIdlist) {
                ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(Long.valueOf(orderId));
                orderLogService.createOrderLog(order.getOrderId(), null, OrderLogType.OrderHandOver, null, OrderProcessFlag.CaiNiao.getInfo(), "115");
                iErpSellerOrderService.updateInnerStatusAndProcess(order.getOrderId(), order.getOrderStatus(), OrderProcessFlag.CaiNiao.getInfo(), "115");
            }


            return R.ok("大包约揽成功");
        } else {
            //组包异常
            return R.fail(body);
        }

    }

    @Override
    public void updateHandoverOrderNew() {
        //找到状态不为arrived （已到达仓库）的交接单延伸表
        List<ErpHandoverOrdersInfo> erpHandoverOrdersInfoList = erpHandoverOrdersInfoMapper.selectList(
                new LambdaQueryWrapper<ErpHandoverOrdersInfo>()
                        .ne(ErpHandoverOrdersInfo::getStatus, "arrived")
                        .ne(ErpHandoverOrdersInfo::getStatus, "canceled")
                        .ne(ErpHandoverOrdersInfo::getStatus, "closed")
                        .ne(ErpHandoverOrdersInfo::getStatus, "closing")
        );
        for (ErpHandoverOrdersInfo orderInfo : erpHandoverOrdersInfoList) {
            handoverContentQuery(orderInfo);
            if (orderInfo.getPrintData() == null) {
                //获取交接单面单
                getHandoverPdf(orderInfo);
            }
            if (orderInfo.getStatus().equals("arrived")) {
                //日志记录 组包成功
                //增加日志
                String orderIds = orderInfo.getOrderIds();
                List<String> orderIdsList = Arrays.asList(orderIds.split(","));
                for (String orderId : orderIdsList) {
                    ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(Long.valueOf(orderId));
                    orderLogService.createOrderLog(order.getOrderId(), null, OrderLogType.OrderHandOverArrived, null, OrderProcessFlag.CaiNiao.getInfo(), "116");
                    iErpSellerOrderService.updateInnerStatusAndProcess(order.getOrderId(), order.getOrderStatus(), OrderProcessFlag.CaiNiao.getInfo(), "116");
                }

            }
        }
    }

    @Override
    public R<Object> selectHandoverOrderDetails(Long handoverOrderId) {
        ErpHandoverOrdersInfo ordersInfo = erpHandoverOrdersInfoMapper.selectOne(
                new LambdaQueryWrapper<ErpHandoverOrdersInfo>().eq(ErpHandoverOrdersInfo::getHandoverOrderId, handoverOrderId));
        if (Objects.isNull(ordersInfo)) {
            return R.fail("未查找到大包信息");
        }
        String orderIds = ordersInfo.getOrderIds();
        List<String> orderIdsList = Arrays.asList(orderIds.split(","));
        List<ErpSellerOrder> orderList = erpSellerOrderMapper.queryOrderByOrderIds(orderIdsList);
        // 执行 SQL 查询，将查询结果添加到 orderList 中
        Map<Long, ErpSellerOrder> orderMap = new HashMap<>();
        for (ErpSellerOrder order : orderList) {
            orderMap.put(order.getOrderId(), order);
        }

        List<ErpSellerHandoverOrder> erpSellerHandoverOrderArrayList = new ArrayList<>();
        for (String id : orderIdsList) {
            ErpSellerOrder order = orderMap.get(Long.valueOf(id));
            ErpSellerHandoverOrder orderInfo = new ErpSellerHandoverOrder();
            orderInfo.setOrderId(order.getOrderId());
            orderInfo.setOrderStatus(order.getOrderStatus());
            orderInfo.setGmtCreate(order.getGmtCreate());
            orderInfo.setLeftEndGoodTime(order.getLeftEndGoodTime());
            orderInfo.setSellerLoginId(order.getSellerLoginId());
            orderInfo.setErpInnerOrderStatus(order.getErpInnerOrderStatus());
            List<ErpWarehouseOrderInfo> erpWarehouseOrderInfoList = erpWarehouseOrderInfoMapper.selectList(new LambdaQueryWrapper<ErpWarehouseOrderInfo>().eq(ErpWarehouseOrderInfo::getTradeOrderId, id).last("limit 1"));
            if (!erpWarehouseOrderInfoList.isEmpty()) {
                for (ErpWarehouseOrderInfo erpWarehouseOrderInfo : erpWarehouseOrderInfoList) {
                    if (orderInfo.getSolutionCode() == null) {
                        orderInfo.setSolutionCode(erpWarehouseOrderInfo.getSolutionCode());
                    } else {
                        orderInfo.setSolutionCode(orderInfo.getSolutionCode() + "," + erpWarehouseOrderInfo.getSolutionCode());
                    }
                    if (orderInfo.getIntlTrackingNo() == null) {
                        orderInfo.setIntlTrackingNo(erpWarehouseOrderInfo.getIntlTrackingNo());
                    } else {
                        orderInfo.setIntlTrackingNo(orderInfo.getIntlTrackingNo() + "," + erpWarehouseOrderInfo.getIntlTrackingNo());
                    }
                }
            }
            List<ErpSellerChildOrder> childOrderList = erpSellerChildOrderMapper.selectList(
                    new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, id)
            );
            if (!childOrderList.isEmpty()) {
                orderInfo.setPhotoProduct(childOrderList.stream().map(e -> e.getSnapshotSmallPhotoPath()).collect(Collectors.toList()));
            }
            erpSellerHandoverOrderArrayList.add(orderInfo);
        }
        return R.ok(erpSellerHandoverOrderArrayList);
    }


    @Override
    public TableDataInfo<ErpHandoverOrdersInfoSelVo> selectHandoverOrderList(PageQuery pageQuery, ErpHandoverOrdersInfoSelBo bo) {
        Page<ErpHandoverOrdersInfoSelVo> variedOrderPageList = erpHandoverOrdersInfoMapper.selectHandoverOrderList(pageQuery.build(), bo);
        variedOrderPageList.setTotal(variedOrderPageList.getTotal());
        return TableDataInfo.build(variedOrderPageList);
    }

    /**
     * 获取组包单详细信息
     */
    public void handoverContentQuery(ErpHandoverOrdersInfo erpHandoverOrderInfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("sellerId", erpHandoverOrderInfo.getMainStoreId());
        //LP开头
        map.put("order_code", erpHandoverOrderInfo.getHandoverContentCode());
        //4px开头
//        map.put("tracking_number", "4PX0017182139");
//        Object userInfo = JSONObject.toJSON(handoverOrderInfo.getUser_info());
        map.put("user_info", "{\"top_user_key\":\"" + erpHandoverOrderInfo.getUserInfo() + "\"}");
        map.put("client", erpHandoverOrderInfo.getClient());
        map.put("locale", "zh_CN");
        //获取组包单详细信息
        R<Object> objectR = remoteAeLogisticsService.handoverContentQuery(map);
        //解析信息
        String body = JSONObject.toJSONString(objectR.getData());
        System.out.println(body);

        //创建对象 - 菜鸟组包延伸表
        Integer code = JSONObject.parseObject(body)
                .getInteger("code");
        if (code == 200) {
            String data = JSONObject.parseObject(body)
                    .getJSONObject("msg")
                    .getJSONObject("cainiao_global_handover_content_query_response")
                    .getJSONObject("result")
                    .getString("data");

            erpHandoverOrderInfo.setOrderCode(JSONObject.parseObject(data).getString("order_code"));
            erpHandoverOrderInfo.setTrackingNumber(JSONObject.parseObject(data).getString("tracking_number"));
            erpHandoverOrderInfo.setStatus(JSONObject.parseObject(data).getString("status"));
            erpHandoverOrderInfo.setStatusName(JSONObject.parseObject(data).getString("status_name"));

            //保存交接单参数
            erpHandoverOrdersInfoMapper.insertOrUpdate(erpHandoverOrderInfo);
        }
    }

    /**
     * 获取交接单面单
     */
    public void getHandoverPdf(ErpHandoverOrdersInfo erpHandoverOrderInfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("sellerId", erpHandoverOrderInfo.getMainStoreId());
        //LP开头
//        map.put("handover_content_id", "10044624822");
        map.put("handover_content_id", erpHandoverOrderInfo.getHandoverContentId());
        //4px开头
        map.put("type", "1");
        map.put("user_info", "{\"top_user_key\":\"" + erpHandoverOrderInfo.getUserInfo() + "\"}");
        map.put("client", erpHandoverOrderInfo.getClient());
        map.put("locale", "zh_CN");
        R<Object> handoverPdf = remoteAeLogisticsService.getHandoverPdf(map);
        //解析信息
        String body = JSONObject.toJSONString(handoverPdf.getData());
        System.out.println(body);
        if (!body.contains("error_response")) {
            String bodyMsg =
                    JSONObject.parseObject(body)
                            .getJSONObject("msg")
                            .getJSONObject("cainiao_global_handover_pdf_get_response")
                            .getJSONObject("result")
                            .getJSONObject("data")
                            .getString("body");
            erpHandoverOrderInfo.setPrintData(bodyMsg);
            erpHandoverOrdersInfoMapper.updateById(erpHandoverOrderInfo);
        }

    }

    @Override
    public R<Object> getOrderExpressSheet(Long handoverOrderId) {
        //1、根据子订单id查找到交接单信息
        ErpHandoverOrdersInfo handoverOrderInfo = erpHandoverOrdersInfoMapper.selectOne(
                new LambdaQueryWrapper<ErpHandoverOrdersInfo>().like(ErpHandoverOrdersInfo::getHandoverOrderId, handoverOrderId)
        );
        if (handoverOrderInfo != null) {
            if (handoverOrderInfo.getPrintData() != null) {

                Map<String, Object> map = new HashMap<>();
                map.put("stringMsg", handoverOrderInfo.getRemark());
                map.put("printData", handoverOrderInfo.getPrintData());
                return R.ok(map, "已查到");

            } else {
                return R.fail("暂无面单");
            }

        } else {
            return R.fail("未查找到该交接单");
        }
    }


}

